package com.dhu.stylefit.controller;

import com.dhu.stylefit.Response;
import com.dhu.stylefit.dto.ClothesDTO;
import com.dhu.stylefit.dto.UsersDTO;
import com.dhu.stylefit.service.UsersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api")
@CrossOrigin(origins = "*")
public class UsersController {

    @Autowired
    private UsersService usersService;

    //获取用户信息
    @GetMapping("/users/{id}")
    public Response<UsersDTO> getUsersById(@PathVariable long id){
        try{
            return Response.newSuccess(usersService.getUsersById(id));
        }catch (Exception e){
            return Response.newFail("Failed to find user by id: "+id +" "+ e.getMessage());
        }
    }

    //增加用户信息
    @PostMapping("/users")
    public Response<Long> addNewUsers(@RequestBody UsersDTO usersDTO) {
        try{
            return Response.newSuccess(usersService.addNewUsers(usersDTO));
        }catch (Exception e){
            return Response.newFail("Failed to add user:" + e.getMessage());
        }

    }

    //删除用户信息
    @DeleteMapping("/users/{id}")
    public Response<String> deleteUsersById(@PathVariable long id) {
        try {
            usersService.deleteUsersById(id);
            return Response.newSuccess("Users deleted successfully");
        } catch (Exception e) {
            return Response.newFail("Failed to delete users: " + e.getMessage());
        }
    }

    //更新用户信息
    @PutMapping("/users/{id}")
    public Response<UsersDTO> updateUsersById(@PathVariable long id,@RequestBody UsersDTO usersDTO){
        try {
            usersDTO.setUser_id(id);
            UsersDTO updatedUsers = usersService.updateUsersById(usersDTO);
            if (updatedUsers != null) {
                return Response.newSuccess(updatedUsers);
            }
            return Response.newFail("Users not found for update");
        } catch (Exception e) {
            e.printStackTrace();
            return Response.newFail("Failed to update Users: " + e.getMessage());
        }
    }

    /**
     * 根据邮箱获取用户信息
     * @param email 用户邮箱（通过路径变量传递）
     * @return 用户信息或错误响应
     */
    @GetMapping("/users/email/{email}")
    public Response<UsersDTO> getUsersByEmail(@PathVariable String email) {
        try {
            // 1. 校验邮箱格式
            if (!isValidEmail(email)) {
                return Response.newFail("Invalid email format");
            }

            // 2. 调用Service层查询用户
            UsersDTO user = usersService.getUsersByEmail(email);
            if (user != null) {
                return Response.newSuccess(user);
            } else {
                return Response.newFail("User not found with email: " + email);
            }
        } catch (Exception e) {
            return Response.newFail("Failed to fetch user by email: " + e.getMessage());
        }
    }

    // 邮箱格式校验
    private boolean isValidEmail(String email) {
        String regex = "^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,6}$";
        return email.matches(regex);
    }

    // 用户登录
    @PostMapping("/login")
    public Response<String> loginUser(@RequestBody UsersDTO usersDTO) {
        try {
            String token = usersService.loginUser(usersDTO);
            if (token != null) {
                return Response.newSuccess(token);
            } else {
                Response<String> failResponse = new Response<>();
                failResponse.setSuccess(false);
                failResponse.setErrorMsg("Invalid username or password");
                return failResponse;
            }
        } catch (IllegalArgumentException e) {
            Response<String> failResponse = new Response<>();
            failResponse.setSuccess(false);
            failResponse.setErrorMsg(e.getMessage());
            return failResponse;
        } catch (Exception e) {
            Response<String> failResponse = new Response<>();
            failResponse.setSuccess(false);
            failResponse.setErrorMsg("Login failed due to internal error: " + e.getMessage());
            return failResponse;
        }
    }

    // 用户注册
    @PostMapping("/register")
    public Response<String> registerUser(@RequestBody UsersDTO usersDTO) {
        try {
            String result = usersService.registerUser(usersDTO);
            if (result != null) {
                // 注册成功
                return Response.newSuccess(result);
            } else {
                // 注册失败
                Response<String> failResponse = new Response<>();
                failResponse.setSuccess(false);
                failResponse.setErrorMsg("Registration failed");
                return failResponse;
            }
        } catch (IllegalArgumentException e) {
            // 捕获服务层抛出的异常，返回包含异常信息的错误响应
            Response<String> failResponse = new Response<>();
            failResponse.setSuccess(false);
            failResponse.setErrorMsg(e.getMessage());
            return failResponse;
        } catch (Exception e) {
            // 捕获其他未知异常，返回包含通用错误信息和异常信息的错误响应
            Response<String> failResponse = new Response<>();
            failResponse.setSuccess(false);
            failResponse.setErrorMsg("Registration failed due to internal error: " + e.getMessage());
            return failResponse;
        }
    }
}
